#include<iostream>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<cstring>
#include<string>
#include<sys/socket.h>

using namespace std;

void Usage(char* head)
{
    cout<<"Use Err"<<endl; 
    cout<<head<<" ip port"<<endl;
}

int main(int argc,char*argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
    }

    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        return 1;
    }

    struct sockaddr_in local;
    memset(&local,0,sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(atoi(argv[2]));
    local.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t len = sizeof(local);

    while(true)
    {
        string buffer;
        cout<<"Enter # ";
        getline(std::cin,buffer);
        ssize_t n = sendto(sockfd,buffer.c_str(),buffer.size(),0,(struct sockaddr*)&local,len);
        if(n > 0)
        {
            char retbuffer[1024];
            ssize_t n = recvfrom(sockfd,retbuffer,sizeof(retbuffer)-1,0,(struct sockaddr*)&local,&len);
            if(n > 0)
            {
                cout<<"server echo # "<<retbuffer<<endl;
            }
            else{
                break;
            }
        }
        else
        {
            break;
        }
    }

    return 0;
}